package com.chenwei.design.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author: chenwei
 * @date: 2021/3/28 18:11
 */
public class CglibProxyFactory implements MethodInterceptor {

    //1.维护目标对象
    private Object target;
    //2.构造器，传入别代理对象
    public CglibProxyFactory(Object target){
        this.target=target;
    }

    //3.获取代理对象
    public Object getProxyInstance(){
        //1.创建一个工具类
        Enhancer enhancer = new Enhancer();
        //2.设置父类
        enhancer.setSuperclass(target.getClass());
        //3.设置回调函数
        enhancer.setCallback(this);
        //4.创建子类对象即代理对象
        return enhancer.create();

    }

    //重写  intercept 方法，会调用目标对象的方法
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        System.out.println("Cglib代理开始前的操作");
        Object object = method.invoke(target, objects);
        System.out.println("Cglib代理后的操作");
        return object;
    }
}
